import sys
from PyQt5 import QtCore,  QtWidgets
from PyQt5.QtCore import Qt
from ui_todo import Ui_Form
import copy


class TodoModel(QtCore.QAbstractListModel):
    def __init__(self, todos):
        super().__init__()
        self.todos = copy.copy(todos)

    def data(self, index, role):
        if role == Qt.DisplayRole:
            text = self.todos[index.row()]
            return text

    def rowCount(self, index):
        return len(self.todos)


class DlgArr(QtWidgets.QDialog):
    ui = Ui_Form()

    def __init__(self, arr, parent=None):
        super().__init__( parent)
        self.ui.setupUi(self)
        # self.setWindowTitle("方法编号")
        self.model = TodoModel(arr)
        self.ui.todoView.setModel(self.model)
        self.ui.addButton.pressed.connect(self.add)
        self.ui.deleteButton.pressed.connect(self.delete)
        # self.ui.completeButton.pressed.connect(self.complete)
        self.ui.btn_ok.clicked.connect(self.ok)
        self.ui.btn_cancel.clicked.connect(self.cancel)

    def ok(self):
        self.accept()

    def cancel(self):
        self.reject()

    def add(self):
        """
        Add an item to our todo list, getting the text from the QLineEdit .todoEdit
        and then clearing it.
        """
        text = self.ui.todoEdit.text()
        # if text:  # Don't add empty strings.
        # Access the list via the model.
        self.model.todos.append(text)
        # Trigger refresh.        
        self.model.layoutChanged.emit()
        #  Empty the input
        self.ui.todoEdit.setText("")
        self.save()

    def delete(self):
        indexes = self.ui.todoView.selectedIndexes()
        if indexes:
            # Indexes is a list of a single item in single-select mode.
            index = indexes[0]
            # Remove the item and refresh.
            del self.model.todos[index.row()]
            self.model.layoutChanged.emit()
            # Clear the selection (as it is no longer valid).
            self.ui.todoView.clearSelection()
            self.save()

    def save(self):
        pass


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = DlgArr([])
    window.show()
    app.exec()
